﻿<script setup lang="ts" name="UserManagement">
import { transformI18n } from '@/plugins/i18n'
import UserAddEdit from './components/userAddEdit.vue'
import { user } from '@/api/user'
import { getDepartmentList } from '@/api/department'
import useDictionaryEntry from '@/hooks/useDictionaryEntry'
import { cloneDeep } from 'lodash-es'
const { getDictionaryEntryData } = useDictionaryEntry()
const statusList = ref([])
const pageData:any = ref({
  listData: {
    total: 0,
    data: []
  },
  searchData: {
    departmentID: '',
    title: '',
    status: 1
  }
})
const pageIndex = ref(1)
const pageSize = ref(20)

// 页面数据条数改变重新获取数据
const handleSizeChange = (val: number) => {
  pageSize.value = val
  pageIndex.value = 1
  getInitData()
}
// 当前页改变重新获取数据
const handleCurrentChange = (val: number) => {
  pageIndex.value = val
  getInitData()
}
// 重置页面数据
const resetPageData = () => {
  pageData.value.listData.data = []
  pageData.value.listData.total = 0
}
// 获取当前查询条件下的数据
const getInitData = () => {
  resetPageData()
  const result: any = {}
  result.pageIndex = pageIndex.value
  result.pageSize = pageSize.value
  result.name = pageData.value.searchData.title
  user.list(result, { config: { showLoading: false, mockEnable: true } }).then((res:any) => {
    console.log(res)
    if (res.data && res.data.length > 0) {
      setTimeout(() => {
        pageData.value.listData.data = res.data
        pageData.value.listData.total = res.total
      }, 1000)
    }
  })
}
// 查询条件重置
const resetSearch = () => {
  pageData.value.searchData.title = ''
  pageData.value.searchData.status = 1
  getInitData()
}

const userDialog = ref(null)
// 新增事件
const add = () => {
  userDialog.value.showDialog()
}
// 编辑事件
const edit = (item) => {
  userDialog.value.showDialog(item)
}

const deleteRow = (v) => {
  const msg = transformI18n('page.确定删除吗？', true)
  ElMessageBox.alert(msg, transformI18n('moduleTitle.警告', true), {
    showCancelButton: true,
    confirmButtonText: transformI18n('buttons.buttonConfirm', true),
    cancelButtonText: transformI18n('buttons.buttonCancel', true),
    type: 'warning',
    callback: (action) => {
      if (action === 'confirm') {
        ElMessage({
          type: 'info',
          message: `操作: 点击了确认`
        })
      } else {
        ElMessage({
          type: 'info',
          message: `操作: 点击了取消`
        })
      }
    }
  })
}

const resetPassword = (v) => {
  const msg = transformI18n('page.确定重置密码吗？', true)
  ElMessageBox.alert(msg, transformI18n('moduleTitle.警告', true), {
    showCancelButton: true,
    confirmButtonText: transformI18n('buttons.buttonConfirm', true),
    cancelButtonText: transformI18n('buttons.buttonCancel', true),
    type: 'warning',
    callback: (action) => {
      if (action === 'confirm') {
        ElMessage({
          type: 'info',
          message: `操作: 点击了确认`
        })
      } else {
        ElMessage({
          type: 'info',
          message: `操作: 点击了取消`
        })
      }
    }
  })
}
const getStatusList = async () => {
  statusList.value = await getDictionaryEntryData({
    label: '',
    status: 2,
    type: 'enable_number'
  })
}
getStatusList()

const departmentSearch = ref({
  name: ''
})
const departmentList = ref([])
const expandNodes = ref([])
// 获取当前查询条件下的数据
const getDepartmentData = () => {
  expandNodes.value = []
  const result: any = {}
  result.name = departmentSearch.value.name
  getDepartmentList(result, { config: { showLoading: false, mockEnable: true } }).then((res:any) => {
    console.log(res)
    if (res.data && res.data.length > 0) {
      setTimeout(() => {
        departmentList.value = dataToTree(res.data)
        departmentList.value.forEach((item) => {
          expandNodes.value.push(item.id)
        })
      }, 1000)
    }
  })
}
const dataToTree = (data) => {
  const dataArr = cloneDeep(data)
  const parents = dataArr.filter(function (item: any) {
    return item.pid === 0
  })
  const children = dataArr.filter(function (item: any) {
    return item.pid !== 0
  })
  // 递归处理动态路由层级
  convert(parents, children)
  return parents
}
const convert = (parents: any, children: any) => {
  parents.forEach(function (item: any) {
    item.value = item.id
    item.label = item.name
    item.children = []
    children.forEach(function (current: any, index: any) {
      if (current.pid === item.id) {
        const temp = children.filter(function (v: any, idx: any) {
          return idx !== index
        }) // 删除已匹配项，这里未使用JSON.parse(JSON.stringify(children))是因为路由的component已经是函数形式，再格式化后，模块导入功能丢失，会导致找不到模块
        item.children.push(current)
        convert([current], temp) // 递归
      }
    })
  })
}
const treeProps = ref({
  children: 'children',
  label: 'label'
})
const handleNodeClick = (v) => {
  console.log(v)
  pageData.value.searchData.departmentID = v.id
  getInitData()
}
onMounted(() => {
  getDepartmentData()
  getInitData()
})
</script>

<template>
  <div class="user-page">
    <el-container>
      <el-aside width="240px" class="flex">
        <el-card shadow="hover" class="flex flex-1 flex-col">
          <template #header>
            <div class="card-header">
              <el-input v-model="departmentSearch.name" :placeholder="$t('page.部门名称')">
                <template #append>
                  <el-button icon="Search" />
                </template>
              </el-input>
            </div>
          </template>
          <el-scrollbar>
            <el-tree :data="departmentList" :props="treeProps" @node-click="handleNodeClick" node-key="value" auto-expand-parent :highlight-current="true" :default-expanded-keys="expandNodes" />
          </el-scrollbar>
        </el-card>
      </el-aside>
      <el-container>
        <el-card shadow="hover" class="flex flex-1">
          <el-form :inline="true">
            <el-form-item :label="$t('page.账号姓名')">
              <el-input v-model="pageData.searchData.title" :placeholder="$t('placeholders.请输入') + $t('page.账号或姓名')" />
            </el-form-item>
            <el-form-item :label="$t('page.状态')">
              <el-radio-group class="radio-button" v-model="pageData.searchData.status">
                <el-radio-button v-for="(item, index) in statusList" :key="index" :label="item.value">{{ $t('page.' + item.label) }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="getInitData">{{ $t('buttons.buttonSearch') }}</el-button>
              <el-button icon="Refresh" @click="resetSearch">{{ $t('buttons.buttonReset') }}</el-button>
              <el-button type="success" icon="Plus" @click="add()">{{ $t('buttons.buttonCreate') }}{{ $t('page.用户') }}</el-button>
            </el-form-item>
          </el-form>
          <div class="flex-1 table-layout">
            <div class="table-wrap">
              <el-table :data="pageData.listData.data" border>
                <el-table-column type="index" :label="$t('page.序号')" width="60" />
                <el-table-column prop="account" :label="$t('page.账号')" min-width="120" />
                <el-table-column prop="userName" :label="$t('page.姓名')" min-width="120" />
                <el-table-column prop="department" :label="$t('page.部门')" min-width="120" />
                <el-table-column prop="phone" :label="$t('page.电话')" min-width="120" />
                <el-table-column prop="email" :label="$t('page.邮箱')" min-width="180" />
                <el-table-column prop="role" :label="$t('page.角色')" min-width="190" align="center">
                  <template #default="scope">
                    <el-tag v-for="(item, index) in scope.row.role" :key="index">{{ item }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="status" :label="$t('page.状态')" width="90" align="center">
                  <template #default="scope">
                    <el-tag :type="scope.row.status ? 'success' : 'danger'">{{ scope.row.status ? $t('page.启用') : $t('page.停用') }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="remark" :label="$t('page.备注')" min-width="240" />
                <el-table-column prop="operate" :label="$t('page.操作')" width="240" align="center" fixed="right">
                  <template #default="scope">
                    <el-button type="primary" icon="Edit" @click="edit(scope.row)"></el-button>
                    <el-button type="danger" icon="Delete" @click="deleteRow(scope.row)"></el-button>
                    <el-button type="warning" @click="resetPassword(scope.row)">{{ $t('buttons.重置密码') }}</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <el-pagination
            v-if="pageData.listData.total > 0"
            v-model:currentPage="pageIndex"
            v-model:page-size="pageSize"
            :page-sizes="[20, 40, 80, 120]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageData.listData.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </el-card>
      </el-container>
    </el-container>
    <UserAddEdit ref="userDialog" :listData="departmentList"></UserAddEdit>
  </div>
</template>

<style scoped lang="scss">
.user-page {

  >.el-container {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    padding: var(--el-space);

    >.el-aside {
      margin-right: var(--el-space);
      overflow: inherit;

      .el-card {
        :deep(.el-card__header) {
          padding: calc(var(--el-space) - 5px);
        }

        :deep(.el-card__body) {
          position: relative;
          display: flex;
          flex: 1;
          padding: 0;

          .el-scrollbar {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;

            .el-scrollbar__wrap {
              padding: calc(var(--el-space) / 2);
            }
          }
        }
      }
    }

    .el-container {
      .el-card {
        :deep(.el-card__body) {
          display: flex;
          flex: 1;
          flex-direction: column;
        }
      }
    }
  }
}

.table-layout {
  position: relative;
  margin: var(--el-space) 0 0;

  .table-wrap {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;

    .el-table {
      width: 100%;
      height: 100%;

      .el-tag {
        margin: 2px;
      }
    }
  }
}

.el-pagination {
  align-items: center;
  justify-content: flex-end;
  margin: var(--el-space) 0 0;
}
</style>
